# _*_ encoding:utf-8 _*_
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def get_edges_collection(filename):
    edges_collection = []
    tree = ET.ElementTree(file=filename)
    for child_of_root in tree.getroot():
        if child_of_root.tag == 'edge':
            shapes = child_of_root[0].attrib['shape']
            edge = {}
            edge.setdefault('id', child_of_root.attrib['id'])
            edge.setdefault('points', [])
            for point in shapes.split(' '):
                x, y = map(float, point.split(','))
                edge['points'].append((x, y))
            edges_collection.append(edge)
    return edges_collection


def tuple2str(a):
    return "{0},{1}".format(a[0], a[1])


def format_item(item):
    return item['id'] + "@" + ' '.join(map(tuple2str, item['points'])) + '\n'


def str2tuple(s):
    return map(float, s.split(','))


def parse_line(line):
    edge = {}
    id, points = line.strip('').split('@')
    edge.setdefault('id', id)
    edge.setdefault('points', map(str2tuple, points.split(' ')))
    return edge


def save_edges(edges_collection, filename, format_, mode='wb'):
    fp = open(filename, mode)
    for edge in edges_collection:
        fp.write(format_(edge))
    fp.close()


def load_edges(filename, parse_):
    fp = open(filename, "rb")
    edges_collection = []
    for line in fp.readlines():
        edges_collection.append(parse_(line))
    return edges_collection


def main():
    read_name = '../../data/hangzhou1.net.xml'
    write_name = '../../data/hangzhou1.edges.txt'
    save_edges(get_edges_collection(read_name), write_name, format_item)

if __name__ == '__main__':
    main()
